package com.linkage.seapeak.activity.project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.PDFViewActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingActivity;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.base.BaseWhiteCreateActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.seapeak.recyclebundle.BaseHolder;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class DissentActionActivity extends BaseWhiteCreateActivity {

    private String projectId;
    private String crRevObjeId;
    private String creditorId;

    private LinearLayout infoLayout;
    private TextView adversText;
    private TextView replyMode;
    private LinearLayout showInfo;
    private EditText replyAdver;

    private RecyclerView recycler_pdf_file;
    private List<TaskAtta> pdfList = new ArrayList<>();

    private RecyclerView recyclerShowImgs;
    private List<UploadImage> imageListShow = new ArrayList<>();
    private GridImagesAdapter imgAdapterShow;

    private RecyclerView recyclerAppendImgs;
    private List<UploadImage> imageListAppend = new ArrayList<>();
    private GridImagesAdapter imgAdapterAppend;

    private TextView textSum;
    private TextView menuAction;

    private ItemData mInfo;

    private PublicNoticeDialog noticeDialog;

    public static void start(Context context, String projectId, String creditorId,
                             String crRevObjeId) {
        Intent intent = new Intent(context, DissentActionActivity.class);
        intent.putExtra("projectId", projectId);
        intent.putExtra("creditorId", creditorId);
        intent.putExtra("crRevObjeId", crRevObjeId);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dissent_reply, "异议信息");
        projectId = getIntent().getStringExtra("projectId");
        creditorId = getIntent().getStringExtra("creditorId");
        crRevObjeId = getIntent().getStringExtra("crRevObjeId");

        initView();
    }

    private void initView() {
        infoLayout = (LinearLayout) findViewById(R.id.info_layout);
        adversText = (TextView) findViewById(R.id.advers_text);
        replyMode = (TextView) findViewById(R.id.reply_mode);
        showInfo = (LinearLayout) findViewById(R.id.show_info);
        replyAdver = (EditText) findViewById(R.id.reply_adver);
        recyclerAppendImgs = (RecyclerView) findViewById(R.id.recycler_append_imgs);
        recyclerShowImgs = (RecyclerView) findViewById(R.id.recycler_show_imgs);
        recycler_pdf_file = (RecyclerView) findViewById(R.id.recycler_pdf_file);
        textSum = (TextView) findViewById(R.id.text_sum);

        recycler_pdf_file.setLayoutManager(new LinearLayoutManager(this,  LinearLayoutManager.VERTICAL,
                false));

        /**
         * PDF 的适配器展示
         */
        recycler_pdf_file.setAdapter(new BaseRecyclerAdapter<PdfHolder>() {
            @NonNull
            @Override
            public PdfHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                return new PdfHolder(LayoutInflater.from(DissentActionActivity.this).inflate(R.layout.item_only_text, viewGroup, false));
            }

            @Override
            public void onBindViewHolder(@NonNull PdfHolder viewHolder, int i) {
                TaskAtta item = pdfList.get(i);
                viewHolder.itemText.setText(item.getAttachmentName());
                viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(DissentActionActivity.this, PDFViewActivity.class);
                        intent.putExtra("url", item.getAttachmentWatermarkAddress());
                        startActivity(intent);
                    }
                });
            }

            @Override
            public int getItemCount() {
                return pdfList == null ? 0 : pdfList.size();
            }
        });
        /**
         * PDF 的适配器展示
         */


        recyclerShowImgs.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL,
                false));
        imgAdapterShow = new GridImagesAdapter(this, TYPE_PREVIEW);
        imgAdapterShow.setList(imageListShow);
        recyclerShowImgs.setAdapter(imgAdapterShow);

        recyclerAppendImgs.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL,
                false));
        imgAdapterAppend = new GridImagesAdapter(this, TYPE_EDIT);
        imgAdapterAppend.setList(imageListAppend);
        recyclerAppendImgs.setAdapter(imgAdapterAppend);

        replyAdver.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String tempStr = replyAdver.getText().toString();
                if (tempStr.length() < 300) {
                    textSum.setText(tempStr.length() + "/300");
                } else {
                    replyAdver.setText(tempStr.substring(0, 300));
                    textSum.setText("300/300");
                }
            }
        });

        menuAction = (TextView) addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendReply();
            }
        }, "完成", 0));
        menuAction.setVisibility(View.GONE);
        replyMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInfo != null) {
                    infoLayout.setVisibility(View.GONE);
                    menuAction.setVisibility(View.VISIBLE);
                    setTitle("回复异议");
                } else {
                    showToast("数据异常");
                }
            }
        });
        showInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoLayout.setVisibility(View.VISIBLE);
                menuAction.setVisibility(View.GONE);
                setTitle("异议信息");
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getDissentDetail();
    }

    @Override
    public void onBackPressed() {
        if (menuAction.getVisibility() != View.VISIBLE || replyAdver.getText().toString().length() == 0) {
            super.onBackPressed();
            return;
        }

        noticeDialog = new PublicNoticeDialog(DissentActionActivity.this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.btn_save_notice) {
                    DissentActionActivity.super.onBackPressed();
                } else {
                    noticeDialog.dismiss();
                }
            }
        }, 1, "提示", "放弃编辑？",
                "否", "是");
        noticeDialog.show();
    }

    private void getDissentDetail() {
        Network.getAPIService()
                .getDissentDetail(getUserToken(), projectId, crRevObjeId, creditorId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            mInfo = new Gson().fromJson(json.getAsJsonObject("data").toString(), ItemData.class);
                            crRevObjeId = mInfo.id;
                            adversText.setText(mInfo.opinion);

                            if(mInfo.responsesStatus)
                            {
                                replyMode.setVisibility(View.INVISIBLE);
                            }else{
                                replyMode.setVisibility(View.VISIBLE);
                            }

                            pdfList.clear();
                            imageListShow.clear();

                            if (mInfo.questionAttaList != null && mInfo.questionAttaList.size() > 0) {
                                for (int i = 0; i < mInfo.questionAttaList.size(); i++) {
                                    TaskAtta atta = mInfo.questionAttaList.get(i);
//                                    if (atta.getAttachmentSuffix().equals("pdf")) {
//                                        pdfList.add(atta);
//                                        recycler_pdf_file.getAdapter().notifyDataSetChanged();
//                                    } else {
                                        JSONObject obj = new JSONObject();
                                        try {
                                            obj.putOpt("filename", atta.getAttachmentName());
                                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                                            obj.putOpt("filesize", atta.getAttachmentSize());
                                            obj.putOpt("loadUrl", atta.getAttachmentThumbnailAddress());
                                            imageListShow.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                                            imgAdapterShow.notifyDataSetChanged();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
//                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError( Throwable e ) {
                        super.onError(e);
                    }
                });
    }

    private void sendReply() {
        if (TextUtils.isEmpty(replyAdver.getText().toString())) {
            showToast("意见不可为空");
            return;
        }



        noticeDialog = new PublicNoticeDialog(DissentActionActivity.this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.btn_save_notice) {

                    JSONArray fileArr = new JSONArray();



                    for (int i = 0; i < imageListAppend.size(); i++) {
                        if (TextUtils.equals(imageListAppend.get(i).getFilename(), NAME_ADD)) {
                            continue;
                        }
                        JSONObject obj = new JSONObject();
                        try {
                            if (FileUtil.isImage(imageListAppend.get(i).getFilename())) {
                                obj.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                            } else {
                                obj.putOpt("attachmentName", imageListAppend.get(i).getFilename());
                            }
                            obj.putOpt("attachmentDownloadAddress", imageListAppend.get(i).getFilepath());
                            obj.putOpt("attachmentSize", imageListAppend.get(i).getFilesize());
                            obj.putOpt("loadUrl", imageListAppend.get(i).getLoadUrl());
                            fileArr.put(obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }


                    Network.getAPIService()
                            .responseDissent(getUserToken(), projectId, crRevObjeId, replyAdver.getText().toString(), fileArr.toString())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new BaseSubscriber<JsonObject>() {
                                @Override
                                public void onNext(JsonObject json) {
                                    int code = json.get("code").getAsInt();
                                    if (code != 0) {
                                        super.onError(new Throwable(json.get("msg").getAsString()));
                                        showToast(json.get("msg").getAsString());
                                        return;
                                    } else {
                                        showToast("提交成功");
                                        finish();
                                    }
                                }

                                @Override
                                public void onCompleted() {
                                    super.onCompleted();
                                }

                                @Override
                                public void onError( Throwable e ) {
                                    super.onError(e);
                                }
                            });
                } else {
                    noticeDialog.dismiss();
                }
            }
        }, 1, "提示", "发送回复意见？",
                "取消", "确定");
        noticeDialog.show();
    }

    class PdfHolder extends BaseHolder {

        TextView itemText;

        public PdfHolder(@NonNull View itemView) {
            super(itemView);
            itemText = itemView.findViewById(R.id.item_text);
        }
    }

    class ItemData {
        /**
         * id : bc275e7715db48e0918770d9c5efb1cb
         * bankruptcyProjectId : fe459c6944884929b5d35e82f4d51077
         * creditorRightReviewId : 602cc5557ef94d1f9bef4add487c2571
         * title : null
         * opinion : ヾ(❀╹◡╹)ﾉ~略略略
         * creditorId : 0cbc1d4da4a24ec4a3216c4d7a94ec8f
         * opinionTime : 1559575129
         * responses : null
         * responsesStatus : false
         * memberId : null
         * responsesTime : null
         * questionAttaList : []
         * responsesAttaList : []
         * opBy : 0720d92fdaf24411b94a197da3eeb814
         * opAt : 1559575129
         * delFlag : false
         */

        public String id;
        public String bankruptcyProjectId;
        public String creditorRightReviewId;
        public Object title;
        public String opinion;
        public String creditorId;
        public int opinionTime;
        public Object responses;
        public boolean responsesStatus;
        public Object memberId;
        public Object responsesTime;
        public String opBy;
        public int opAt;
        public boolean delFlag;
        public List<TaskAtta> questionAttaList;
        public List<TaskAtta> responsesAttaList;
    }
}
